package com.joymart.compute.service;


import com.joymart.common.system.IdGenerator;
import com.joymart.common.utils.DatetimeUtils;
import com.joymart.compute.model.VitalityPoint;
import com.joymart.compute.repository.VitalityPointRepository;
import com.joymart.order.model.Order;
import com.joymart.user.model.BusinessRole;
import com.joymart.user.model.CachedUser;
import com.joymart.user.service.UserCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jdbc.core.JdbcAggregateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Optional;

@Service
public class VitalityPointService {


    @Autowired
    private VitalityPointRepository vitalityPointRepository;

    @Autowired
    private JdbcAggregateTemplate jdbcAggregateTemplate;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private UserCacheManager userCacheManager;


    public BigDecimal sumUserVitalityPoints(String userId) {
        return Optional.ofNullable(
                vitalityPointRepository.sumUserValidVitalityPoints(userId))
                .orElse(BigDecimal.ZERO);
    }

    @Transactional
    public void computeOrderVitalityPoints(Order order) {
        String buyerId = order.getBuyerId();
        CachedUser buyer = userCacheManager.get(buyerId);
        insertVitalityPointIfNecessary(order, buyer, buyer);
        if(buyer.getUser().getInvitedBy()!=null){
            insertVitalityPointIfNecessary(order, userCacheManager.get(buyer.getUser().getInvitedBy())
                    ,buyer);
        }
    }

    @Transactional
    public void invalidateVitalityPoints(String contributorId) {
        vitalityPointRepository.invalidateVitalityPointByContributorId(contributorId);
    }

    private void insertVitalityPointIfNecessary(Order order, CachedUser owner, CachedUser contributor) {
        if(owner.getBusinessRoles().contains(BusinessRole.AG_SHOP)){
            return; //已经开店的忽略
        }
        VitalityPoint vitalityPoint = new VitalityPoint();
        vitalityPoint.setId(idGenerator.next());
        vitalityPoint.setOrderId(order.getId());
        vitalityPoint.setAmount(order.getTotalPv());
        vitalityPoint.setValid(true);
        vitalityPoint.setOwnerId(owner.getId());
        vitalityPoint.setContributorId(contributor.getId());
        vitalityPoint.setCreatedAt(DatetimeUtils.now());
        jdbcAggregateTemplate.insert(vitalityPoint);
    }


}
